<template>
  <el-card shadow="always">
    <!---- -- -- -- 头部-- -- -- -- -- -- -->
    <div slot="header">
      <!-- 路径导航 -->
       <Breadcrumb/>
    </div>
    <!---- -- -- -- 内容-- -- -- -- -- -- -->
    <!-- 提示 -->
    <el-alert title="消息提示的文案"
              type="info"
              center
              show-icon>
    </el-alert>
    <br>
    <!-- 步骤条 -->
    <el-steps :active="active*1"
              :space="300"
              align-center
              finish-status="success">
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
    </el-steps>
    <br><br>
    <!-- tabs标签页组件 -->
    <el-form :model="formData"
    ref="form"
             :rules="formRules"
             label-width="80px">
      <el-tabs tab-position="left"
               v-model="active"
               @tab-click="handleClick"
               :before-leave="beforeLeave">
        <el-tab-pane label="基本信息"
                     name="0">
          <el-row>
            <el-col :span="18"
                    :offset="3">
              <el-form-item label="商品名称"
                            size="normal"
                            prop="goods_name">
                <el-input v-model="formData.goods_name"
                          size="normal"
                          clearable></el-input>
              </el-form-item>
              <el-form-item label="商品价格"
                            size="normal"
                            prop="goods_price">
                <el-input v-model="formData.goods_price"
                          size="normal"
                          clearable></el-input>
              </el-form-item>
              <el-form-item label="商品数量"
                            size="normal"
                            prop="goods_number">
                <el-input v-model="formData.goods_number"
                          size="normal"
                          clearable></el-input>
              </el-form-item>
              <el-form-item label="商品重量"
                            size="normal"
                            prop="goods_weight">
                <el-input v-model="formData.goods_weight"
                          size="normal"
                          clearable></el-input>
              </el-form-item>
              <el-form-item label="商品分类"
                            size="normal"
                            prop="goods_cat">
                <el-cascader v-model="formData.goods_cat"
                             :options="allCateList"
                             clearable
                             :props="{label:'cat_name',value:'cat_id'}"></el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="商品参数"
                     name="1">
          <el-row>
            <el-col :span="18"
                    :offset="3">

              <el-form-item :label="item.attr_name"
                            v-for="item in manyList"
                            :key="item.attr_id">
                <el-checkbox-group v-model="item.attr_vals">
                  <el-checkbox v-for="val in item.attr_vals"
                               :key="val"
                               :label="val"></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="商品属性"
                     name="2">
          <el-row>
            <el-col :span="18"
                    :offset="3">
              <el-form-item label-width="150px"
                            :label="item.attr_name"
                            v-for="item in onlyList"
                            :key="item.attr_id">
                <el-input v-model="item.attr_vals"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

        </el-tab-pane>
        <el-tab-pane label="商品图片"
                     name="3">
          <!-- action 上传地址 -->
          <el-upload :class="{'avatar-uploader':true, 'limit': formData.pics.length>=3 }"
                     action="http://127.0.0.1:8888/api/private/v1/upload"
                     name="file"
                     list-type="picture-card"
                     :limit="3"
                     :on-success="onSuccess"
                     :on-error="onError"
                     :headers="{ Authorization:token }">
            <!--  加号按钮 -->
            <i slot="default"
               class="el-icon-plus"></i>
            <!-- 文件信息 -->
            <div slot="file"
                 class="img-box"
                 slot-scope="{file}">
              <!-- 小图片 -->
              <img class="el-upload-list__item-thumbnail"
                   :src="file.url"
                   alt="">
              <!-- 三个操作按钮 -->
              <span class="el-upload-list__item-actions">
                <!-- 预览按钮 -->
                <span class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <!-- 预览图片弹框 -->
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%"
                 :src="dialogImageUrl"
                 alt="">
          </el-dialog>
        </el-tab-pane>
        <el-tab-pane label="商品内容"
                     name="4">
          <!-- 编辑器 -->
          <quill-editor v-model="formData.goods_introduce"
                        ref="myQuillEditor">
          </quill-editor>
          <br>
          <el-button type="primary" size="default" @click="addSubmit">增加商品</el-button>

        </el-tab-pane>
      </el-tabs>
    </el-form>
  </el-card>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import lodash from 'lodash'
export default {
  components: {
    quillEditor
  },
  name: 'GoodsAdd',
  data () {
    const user = JSON.parse(localStorage.getItem('HEIMASHOP_USER'))
    return {
      active: 0, // 激活位置下标
      formData: { // 表单数据对象
        goods_name: '',
        goods_cat: [1, 3, 6],
        goods_price: '',
        goods_number: '',
        goods_weight: '',
        goods_introduce: '',
        pics: [],
        attrs: []
      },
      formRules: { // 表单验证规则
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }]
      },
      allCateList: [], // 所有分类
      manyList: [], // 动态参数
      onlyList: [], // 静态属性
      dialogImageUrl: '', // 预览的图片地址
      dialogVisible: false, // 预览弹框是否显示
      token: user.token // 用户的token
    }
  },
  created () {
    this.getAllCateList()
  },
  methods: {
    // 获取所有分类
    async getAllCateList () {
      const { data: res } = await this.$axios.get('/categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.allCateList = res.data
    },
    // 标签页切换后事件
    handleClick () {
      if (this.active * 1 === 1) { // 进入商品参数
        // 获取动态参数
        this.getParamsList('many')
      } else if (this.active * 1 === 2) { // 进入商品属性
        // 获取静态属性
        this.getParamsList('only')
      }
    },
    // 标签切换之前的钩子，如返回false或者reject 就会阻止切换！
    beforeLeave (activeName, oldActiveName) {
      // 需求： 只要进入商品参数(1)和商品属性(2)，且基本信息里面已经选择了分类ID
      if (['1', '2'].includes(activeName)) {
        if (this.formData.goods_cat.length === 0) {
          this.$message.warning('请选择商品分类')
          return false
        }
      }
    },
    // 获取动态参数或静态属性方法
    async getParamsList (activeName) {
      const cateId = this.formData.goods_cat[this.formData.goods_cat.length - 1]
      // 发送请求、错误处理、成功处理
      const { data: res } = await this.$axios.get('/categories/' + cateId + '/attributes?sel=' + activeName)
      if (res.meta.status !== 200) return res.meta.msg
      // 加工数据！ 把 attr_vals 变成一个数组；
      if (activeName === 'many') {
        res.data.forEach(val => {
          if (val.attr_vals) {
            val.attr_vals = val.attr_vals.split(',')
          } else {
            val.attr_vals = []
          }
        })
      }
      this[activeName + 'List'] = res.data
    },
    // 上传成功
    onSuccess (res, file) {
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.formData.pics.push({
        pic: res.data.tmp_path
      })
    },
    // 上传失败
    onError () {
      this.$message.error('服务器错误')
    },
    // 图片预览按钮点击事件
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    addSubmit () {
      this.$refs.form.validate(async valid => {
        // 验证数据
        if (!valid) return this.$message.warning('验证不通过')
        if (this.formData.pics.length === 0) return this.$message.warning('请选择图片')
        if (this.formData.goods_introduce.length === 0) return this.$message.warning('请输入商品详情')
        // 加工数据,建议是在拷贝的一份的基础上面加工！
        const cloneFormData = lodash.assign({}, this.formData)
        cloneFormData.attrs = this.manyList.map(val => {
          return { attr_id: val.attr_id, attr_values: val.attr_vals.join(',') }
        })
        cloneFormData.attrs = this.onlyList.map(val => {
          return { attr_id: val.attr_id, attr_values: val.attr_vals }
        })
        if (cloneFormData.attrs.length === 0) return this.$message.warning('请选择属性数据')
        cloneFormData.goods_cat = this.formData.goods_cat.join(',')
        // 发送数据
        const { data: res } = await this.$axios.post('/goods', cloneFormData)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style scoped lang="less">
/* 一开始模板里面是没有el-upload这个class */
/* 让我们自己写的样式可以穿透到组件内部去 */
.img-box{
  height: 100%;
  display: flex;
  align-items: center;
}
.el-upload-list__item-thumbnail{
  width: 100%;
  height: auto!important;;
}
.border-box{
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    border-radius: 6px;
    box-sizing: border-box;
    width: 148px;
    height: 148px;
    line-height: 146px;
    vertical-align: top;
}
/deep/ .avatar-uploader.limit .el-upload--picture-card{
   display: none;
}

/deep/ .ql-container{
  min-height: 300px;
}
</style>
